<template>
	<div v-if="moduleNameOptions && form.type">
		<el-dialog
			:title="(mode === 'add' ? '新增' : '编辑') + moduleNameOptions[form.type].label + '内容'"
			:visible.sync="dialogVisible"
			:append-to-body="true"
			:close-on-click-modal="false"
			width="850px"
			@close="close"
		>
			<el-form ref="form" v-loading="loading" :model="form" :rules="rules" label-width="120px" label-suffix="：" size="small">
				<div v-for="(v, k) in moduleNameOptions[form.type].params" :key="k">
					<el-form-item v-if="k == 'titleType'" :label="v.label || '标题类型'" prop="titleType">
						<el-select v-model="form.titleType" placeholder="请选择" class="w-400">
							<el-option label="文本标题" value="text" />
							<el-option label="图片标题" value="image" />
						</el-select>
					</el-form-item>
					<el-form-item v-if="(k == 'title' && !form.titleType) || (k == 'title' && form.titleType === 'text')" :label="v.label || '标题'" prop="title">
						<el-input v-model.trim="form.title" maxlength="4" show-word-limit class="w-400" />
					</el-form-item>

					<el-form-item v-if="k == 'subTitle' && form.titleType == 'text'" :label="v.label || '副标题'" prop="subTitle">
						<el-input v-model.trim="form.subTitle" maxlength="4" show-word-limit class="w-400" />
					</el-form-item>

					<el-form-item v-if="(k == 'bg' && !form.titleType) || (k == 'bg' && form.titleType === 'image')" :label="v.label || '背景图'" prop="bg">
						<div class="upload-container">
							<el-upload
								:action="imageUploadUrl"
								:show-file-list="false"
								:headers="{ 'X-BUSINESS-TOKEN': $store.state.user.token }"
								:before-upload="handleImgBefore"
								:on-success="
									(res, file) => {
										return handleImgSuccess(res, file, 'bg');
									}
								"
								:style="{ width: v.width + 'px', height: v.height + 'px' }"
								class="app-uploader-img-plus"
							>
								<el-image v-if="form.bg" :style="{ width: v.width + 'px', height: v.height + 'px' }" :src="fileBaseUrl + form.bg" class="img" fit="contain" />
								<i v-else :style="{ width: v.width + 'px', height: v.height + 'px' }" class="el-icon-plus" />
							</el-upload>
						</div>
						<div style="font-size: 12px">只能上传jpg/png/gif文件，建议像素{{ v.width + ' * ' + v.height }}，且不超过1MB</div>
					</el-form-item>

					<!-- 跳转链接类型 -->
					<el-form-item v-if="k == 'dump'" :label="v.label || '跳转链接'" prop="dump.type">
						<el-radio-group v-model="form.dump.type" size="small">
							<el-radio-button label="EMPTY">无</el-radio-button>
							<el-radio-button label="INSIDE">站内链接</el-radio-button>
							<el-radio-button label="FEATURE">手机功能</el-radio-button>
							<el-radio-button label="WXAPP">小程序</el-radio-button>
							<el-radio-button :label="form.dump.type == 'URL' ? 'URL' : 'URL_KF'">自定义链接</el-radio-button>
						</el-radio-group>
					</el-form-item>

					<div v-if="k == 'dump'">
						<!-- 站内链接 -->
						<el-form-item v-if="form.dump.type === 'INSIDE'" prop="dump.insidePage" label="站内链接">
							<el-button size="small" @click="openInsideLink">选择链接</el-button>
							<div v-if="form.dump.insideParams.remark">链接地址：{{ form.dump.insideParams.remark }}</div>
						</el-form-item>

						<!-- 手机功能-->
						<div v-if="form.dump.type === 'FEATURE'">
							<el-form-item prop="dump.feature" label="手机功能">
								<el-select v-model="form.dump.feature" placeholder="请选择" class="w-400">
									<el-option label="拨打电话" value="CALL" />
									<!--                  <el-option label="微信客服助手" value="CONTACT"/>-->
								</el-select>
							</el-form-item>
							<el-form-item v-if="form.dump.feature === 'CALL'" prop="dump.featureParams.phone" label="电话">
								<el-input v-model="form.dump.featureParams.phone" class="w-400" />
							</el-form-item>
						</div>

						<!-- 小程序 -->
						<div v-if="form.dump.type === 'WXAPP'">
							<el-form-item label="小程序appId" prop="dump.appId"><el-input v-model.trim="form.dump.appId" class="w-400" /></el-form-item>
							<el-form-item label="小程序路径" prop="dump.path"><el-input v-model.trim="form.dump.path" class="w-400" /></el-form-item>
						</div>

						<!-- 公众号推文 -->
						<el-form-item v-if="form.dump.type === 'URL' || form.dump.type === 'URL_KF'" label="推文地址">
							<el-radio-group v-model="tweetType" @change="tweetChange">
								<el-radio label="URL">公众号文章链接</el-radio>
								<el-radio label="URL_KF">企业微信客服链接</el-radio>
							</el-radio-group>
							<div v-if="tweetType == 'URL'">
								<el-form-item prop="dump.url"><el-input v-model.trim="form.dump.url" class="w-400" placeholder="仅支持打开关联的公众号的文章" /></el-form-item>
							</div>
							<div v-else>
								<el-form-item prop="dump.url"><el-input v-model.trim="form.dump.url" class="w-400" placeholder="仅支持打开关联的企业微信客服" /></el-form-item>
								<el-form-item prop="biz.params.corpId"><el-input v-model.trim="form.biz.params.corpId" class="w-400" placeholder="企业ID" /></el-form-item>
								<p>
									可点击查看
									<span style="color: #409eff; cursor: pointer;" @click="operBtn">操作详情</span>
									进行操作。
								</p>
							</div>
						</el-form-item>
					</div>

					<!-- 图片类-->
					<el-form-item v-if="k == 'pic'" :label="v.label || '图片'" prop="pic">
						<div class="upload-container">
							<el-upload
								:action="imageUploadUrl"
								:show-file-list="false"
								:headers="{ 'X-BUSINESS-TOKEN': $store.state.user.token }"
								:before-upload="handleImgBefore"
								:on-success="
									(res, file) => {
										return handleImgSuccess(res, file, 'pic');
									}
								"
								:style="{ width: v.width + 'px', height: v.height + 'px' }"
								class="app-uploader-img-plus"
							>
								<el-image v-if="form.pic" :style="{ width: v.width + 'px', height: v.height + 'px' }" :src="fileBaseUrl + form.pic" class="img" fit="contain" />
								<i v-else :style="{ width: v.width + 'px', height: v.height + 'px' }" class="el-icon-plus" />
							</el-upload>
						</div>
						<div style="font-size: 12px">只能上传jpg/png/gif文件，建议像素{{ v.width + ' * ' + v.height }}，且不超过1MB</div>
					</el-form-item>
				</div>
			</el-form>

			<div slot="footer" class="dialog-footer">
				<el-button size="small" round @click="hide">取 消</el-button>
				<el-button size="small" round type="primary" @click="submit">确 定</el-button>
			</div>
		</el-dialog>

		<!-- 站内链接 -->
		<DialogInsideLink ref="insideLink" />
		<CustomerOperation ref="customerOperationDialog" />
	</div>
</template>

<script>
import { mapGetters } from 'vuex';
import { imgUploadUrl } from '@/api/upload';
import DialogInsideLink from '@/views/wxaBuildModule/views/components/DialogInsideLink';
import wxaBuildConfig from '@/views/wxaBuildModule/config';
import CustomerOperation from '../../../components/DialogInsideLink/components/CustomerOperation.vue';

export default {
	components: {
		DialogInsideLink,
		CustomerOperation
	},
	data() {
		return {
			tweetType: '1', // 自定义链接
			// 表单校验相关
			rules: {
				titleType: [
					{
						required: true,
						message: '请选择',
						trigger: ['blur', 'change']
					}
				],
				title: [
					{
						required: true,
						message: '请输入标题',
						trigger: ['blur', 'change']
					}
				],

				bg: [
					{
						required: true,
						message: '请上传图片',
						trigger: ['blur', 'change']
					}
				],
				pic: [
					{
						required: true,
						message: '请上传图片',
						trigger: ['blur', 'change']
					}
				],
				selectedIcon: [
					{
						required: true,
						message: '请上传选中图标',
						trigger: ['blur', 'change']
					}
				],
				'dump.type': [
					{
						required: true,
						message: '请选择类型',
						trigger: ['blur', 'change']
					}
				],
				'dump.insidePage': [
					{
						required: true,
						message: '请选择链接',
						trigger: ['blur', 'change']
					}
				],
				'dump.url': [
					{
						required: true,
						message: '请输入地址',
						trigger: ['blur', 'change']
					}
				],
				'biz.params.corpId': [
					{
						required: true,
						message: '请输入企业ID',
						trigger: ['blur', 'change']
					}
				],
				'dump.appId': [
					{
						required: true,
						message: '请输入appId',
						trigger: ['blur', 'change']
					}
				],
				'dump.path': [
					{
						required: true,
						message: '请输入',
						trigger: ['blur', 'change']
					}
				],
				'dump.feature': [
					{
						required: true,
						message: '请选择',
						trigger: ['blur', 'change']
					}
				],
				'dump.featureParams.phone': [
					{
						required: true,
						message: '请输入手机号',
						trigger: ['blur', 'change']
					}
				]
			},
			// 配置
			resolve: null,
			reject: null,
			imageUploadUrl: imgUploadUrl,
			moduleNameOptions: null,
			// 状态
			loading: false,
			dialogVisible: null,
			// 数据
			classifyCode: 'DEFAULT',
			mode: 'add',
			form: {
				titleType: 'text',
				bg: '',
				biz: {
					params: '',
					type: 'DUMP'
				},
				color: '',
				content: '',
				dump: {
					appId: '',
					feature: '',
					featureParams: '',
					insidePage: '',
					insideParams: '',
					path: '',
					type: 'EMPTY',
					url: ''
				},
				modules: [],
				pic: '',
				ranking: 0,
				style: '',
				subTitle: '',
				subType: '',
				title: '',
				type: ''
			}
		};
	},
	watch: {
		'form.dump.feature'(val) {
			if (val === 'CALL') {
				if (this.form.dump.featureParams.constructor === Object) {
					if (!this.form.dump.featureParams.hasOwnProperty('phone')) {
						this.form.dump.featureParams.phone = null;
					}
				} else {
					this.form.dump.featureParams = { phone: null };
				}
			}
		},
		'form.dump.type'(val) {
			this.$nextTick(() => {
				this.$refs.form.clearValidate();
				this.tweetChange(val);
			});
		}
	},
	computed: {
		...mapGetters(['fileBaseUrl', 'activePageForm'])
	},
	mounted() {
		this.moduleNameOptions = wxaBuildConfig[this.classifyCode].moduleName;
	},
	methods: {
		/**
		 * 弹框相关
		 */
		open({ mode = 'add', row = '' }) {
			this.mode = mode;
			if (mode === 'edit' && row) {
				if (row.bg) {
					row.titleType = 'image';
				} else {
					row.titleType = 'text';
				}

				// 兼容旧按钮,没有corpId,导致输入失败.
				if (row.biz.params.corpId == undefined) {
					row.biz.params = {
						corpId: null
					};
				}
				this.form = JSON.parse(JSON.stringify(row));
			} else {
				this.defaultForm();
			}
			this.show();
			return new Promise((resolve, reject) => {
				this.resolve = resolve;
				this.reject = reject;
			});
		},

		show() {
			this.dialogVisible = true;
		},

		close() {
			this.loading = false;
			this.$nextTick(() => {
				this.$refs.form.clearValidate();
			});
		},

		hide() {
			this.resolve = null;
			this.reject = null;
			this.dialogVisible = false;
		},

		defaultForm() {
			this.form = {
				titleType: 'text',
				bg: '',
				biz: {
					params: {
						corpId: ''
					},
					type: this.activePageForm.modules[this.activePageForm.activeModuleIndex].biz.type
				},
				color: '',
				content: '',
				dump: {
					appId: '',
					feature: '',
					featureParams: {
						phone: null,
						remark: null
					},
					insidePage: '',
					insideParams: {
						insidePageType: null,
						pageId: null,
						goodsSerial: null,
						remark: null
					},
					path: '',
					type: 'EMPTY',
					url: ''
				},
				modules: [],
				// pic: 'business/1/ce5d11bb-7ca8-47fd-b7ea-93fd64a3c5a6.png',
				pic: '',
				ranking: 0,
				style: '',
				subTitle: '',
				subType: '',
				title: '',
				type: this.activePageForm.modules[this.activePageForm.activeModuleIndex].type
			};
		},

		// 操作详情
		operBtn() {
			this.$refs.customerOperationDialog.open({ roleType: 'qyWx_kf' });
		},

		/**
		 * 数据组
		 */

		/**
		 * 按钮组
		 */
		// 打开选择链接
		openInsideLink() {
			this.$refs.insideLink.open({ row: this.form.dump }).then(res => {
				this.form.dump.insidePage = res.insidePage || null;
				this.form.dump.insideParams = {
					insidePageType: res.insideParams.insidePageType || null,
					pageId: (res.insideParams && res.insideParams.pageId) || null,
					goodsSerial: (res.insideParams && res.insideParams.goodsSerial) || null,
					commonCode: (res.insideParams && res.insideParams.commonCode) || null,
					remark: (res.insideParams && res.insideParams.remark) || null
				};
				this.form.dump.mode = res.mode || null;
				this.form.dump.path = res.path || null;
			});
		},

		// 选择推文地址
		tweetChange(val) {
			this.form.dump.type = val;
			this.tweetType = val;
		},

		// 确 定
		submit() {
			this.$refs.form.validate(valid => {
				if (valid) {
					const params = JSON.parse(JSON.stringify(this.form));
					switch (params.dump.type) {
						case 'EMPTY':
						case 'WXAPP':
						case 'URL':
							params.dump.featureParams = {
								phone: null,
								remark: null
							};
							params.dump.insideParams = {
								insidePageType: null,
								pageId: null,
								goodsSerial: null,
								remark: null
							};
							break;
						case 'URL_KF':
							params.dump.featureParams = {
								phone: null,
								remark: null
							};
							params.dump.insideParams = {
								insidePageType: null,
								pageId: null,
								goodsSerial: null,
								remark: null
							};
							break;
						case 'FEATURE':
							switch (params.dump.feature) {
								case 'CALL':
									params.dump.featureParams.remark = null;
									break;
								case 'CONTACT':
									params.dump.featureParams = {
										phone: null,
										remark: null
									};
									break;
							}
							break;
					}
					if (params.titleType === 'text') {
						params.bg = '';
					} else {
						params.title = '';
						params.subTitle = '';
					}
					this.resolve && this.resolve(params);
					this.hide();
					this.$store.dispatch('setActivePageForm', JSON.parse(JSON.stringify(this.activePageForm)));
				}
			});
		},

		// 上传图标之前
		handleImgBefore(file) {
			return this.beforeUploadImg(file, this, 0, 0, 1, ['JPG', 'PNG', 'GIF']);
		},

		// 上传图标成功
		handleImgSuccess(res, file, type) {
			if (res.code === 0) {
				this.form[type] = res.data.path;
				this.$refs.form.clearValidate([type]);
			} else {
				this.$message.error(res.msg);
			}
		}

		/**
		 * 状态组
		 */

		/**
		 * 方法组
		 */
	}
};
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
.w-400 {
	width: 400px;
}

/* 上传图片 */
.upload-container {
	display: flex;

	.el-icon-plus {
		display: flex;
		justify-content: center;
		align-items: center;
		font-size: 36px;
		color: #8c939d;
	}

	.img {
		display: block;
	}
}
</style>
